<i18n lang="json">
{
  "zh-cn": {
    "accountLogin": "账号密码登录",
    "qrcodeLogin": "扫码登录",
    "intro": "欢迎使用 👋🏻",
    "remember": "记住我",
    "forget": "忘记密码了?",
    "noAccount": "还没有帐号?",
    "register": "注册新帐号",
    "wechatQrcode": "请使用微信扫码登录",
    "testLogin": "账号一键登录",
    "codeTextSucess":"验证码获取成功",
    "codeTextError":"验证码获取失败",
    "loginSuccess": "登录成功，正在跳转...",
    "wechatAuthError": "微信授权失败",
    "form": {
      "account": "用户名",
      "password": "密码",
      "login": "登录",
      "captcha":"验证码",
      "imgCaptcha":"图形验证码",
      "sendCaptcha": "发送验证码",
      "captchaCountdown": "{0} 秒后可重新发送"
    },
    "rules": {
      "account": "请输入用户名",
      "password": "请输入密码",
      "code": "请输入验证码",
      "captcha": "请输入图形验证码"
    }
  },
  "en": {
    "accountLogin": "Account Login",
    "qrcodeLogin": "Scan Login",
    "intro": "Welcome aboard 👋🏻",
    "remember": "Remember Me",
    "forget": "Forget Password?",
    "noAccount": "No Account?",
    "register": "Register New Account",
    "wechatQrcode": "Please use WeChat scan login",
    "testLogin": "Account One-click Login",
    "codeTextSucess":"Get code success",
    "codeTextError":"Get code failed",
    "loginSuccess": "Login success, redirecting...",
    "wechatAuthError": "WeChat authorization failed",
    "form": {
      "account": "Account",
      "password": "Password",
      "login": "Login",
      "captcha": "Captcha",
      "sendCaptcha": "Send Captcha",
      "imgCaptcha":"Graphic verification code",
      "captchaCountdown": "Can resend in {0}s"
    },
    "rules": {
      "account": "Please enter the account",
      "password": "Please enter the password",
      "code": "Please enter the code",
      "captcha": "Please enter the code"
    }
  }
}
</i18n>

<script setup lang="ts">
import apiUser from '@/api/modules/user'
import useUserStore from '@/store/modules/user'
import { FormControl, FormField, FormItem, FormMessage } from '@/ui/shadcn/ui/form'
import storage from '@/utils/storage'
import { toTypedSchema } from '@vee-validate/zod'
import { useForm } from 'vee-validate'
import { useI18n } from 'vue-i18n'
import { toast } from 'vue-sonner'
import * as z from 'zod'

defineOptions({
  name: 'LoginForm',
})

const props = defineProps<{
  account?: string
}>()

const emits = defineEmits<{
  onLogin: [account?: string]
  onRegister: [account?: string]
  onResetPassword: [account?: string]
}>()

const { t } = useI18n()
const userStore = useUserStore()

const title = import.meta.env.VITE_APP_TITLE
const loading = ref(false)

// 登录方式，default 账号密码登录，qrcode 扫码登录
const type = ref<'default' | 'qrcode'>('default')
const imgCaptcha = ref<string>('')
const uuid = ref<string>('')
const form = useForm({
  validationSchema: toTypedSchema(z.object({
    username: z.string().min(1, t('rules.account')),
    password: z.string().min(1, t('rules.password')),
    remember: z.boolean(),
    code: z.string().min(1, t('rules.captcha')),
  })),
  initialValues: {
    username: props.account ?? storage.local.get('login_account') ?? '',
    password: '',
    remember: storage.local.has('login_account'),
    code: '',
  },
})
const wxLoaded = ref(false) // SDK加载状态
const qrCodeGenerated = ref(false) // 二维码生成状态
// 清理二维码容器
function clearQRContainer() {
  const container = document.getElementById('wechatQRCode')
  if (container) {
    container.innerHTML = '' // 清空容器内容
  }
}

// 加载微信JS SDK
function loadWechatSDK() {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script')
    script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
    script.onload = resolve
    script.onerror = reject
    document.head.appendChild(script)
  })
}

// 初始化微信登录
async function initWechatLogin() {
  try {
    if (!wxLoaded.value) {
      await loadWechatSDK()
      wxLoaded.value = true
    }
    clearQRContainer()
    // 将实例赋值给变量（即使后续不使用）
    const wxLoginInstance = new WxLogin({ // [!code ++]
      id: 'wechatQRCode',
      appid: '',
      scope: 'snsapi_login,snsapi_userinfo',
      redirect_uri: encodeURIComponent(''),
      state: Date.now().toString(), // 建议转为字符串
      style: 'black',
      href: '',
      stylelite: 1,
    })
    qrCodeGenerated.value = true
  }
  catch (error) {
    console.error('微信SDK加载失败:', error)
  }
}
// 获取图形验证码
async function getImgCaptcha() {
  apiUser.captchaImage().then((res: any) => {
    if (res.code === 200) {
      uuid.value = res.data.uuid
      refreshCaptcha(res.data.img)
    }
  })
}
// 获取验证码逻辑
async function refreshCaptcha(url: string) {
  try {
    imgCaptcha.value = `data:image/png;base64,${url}`
  }
  catch (error) {
    toast.error(t('codeTextError'))
  }
}

const onSubmit = form.handleSubmit((values) => {
  loading.value = true
  const loginData: any = {
    username: values.username,
    password: values.password,
    uuid: uuid.value,
    code: values.code,
  }
  userStore.login(loginData).then(() => {
    if (values.remember) {
      storage.local.set('login_account', values.username)
    }
    else {
      storage.local.remove('login_account')
    }
    emits('onLogin', values.username)
  }).finally(() => {
    getImgCaptcha()
    loading.value = false
  })
})
// 标签切换处理
function changeType() {
  if (type.value === 'qrcode') {
    if (!qrCodeGenerated.value) {
      initWechatLogin()
    }
    else {
      clearQRContainer()
      initWechatLogin() // 重新生成新二维码
    }
  }
}
onMounted(() => {
  getImgCaptcha()
})
onBeforeUnmount(() => {
  // 清理微信登录相关DOM
  const wxContainer = document.getElementById('wechatQRCode')
  wxContainer?.remove()
})
</script>

<template>
  <div class="min-h-500px w-full flex-col-stretch-center p-12">
    <FaBlurReveal :delay="0.2" :duration="0.4" class="mb-6 space-y-2">
      <h3 class="text-4xl color-[var(--el-text-color-primary)] font-bold">
        {{ t('intro') }}
      </h3>
      <p class="text-sm text-muted-foreground lg:text-base">
        {{ title }}
      </p>
    </FaBlurReveal>
    <div class="mb-4">
      <FaTabs
        v-model="type"
        :list="[
          { label: t('accountLogin'), value: 'default' },
          // { label: t('qrcodeLogin'), value: 'qrcode' },
        ]" class="inline-flex" @click="changeType"
      />
    </div>
    <div v-show="type === 'default'">
      <form @submit="onSubmit">
        <FormField v-slot="{ componentField, errors }" name="username">
          <FormItem class="relative pb-6 space-y-0">
            <FormControl>
              <FaInput type="text" :placeholder="t('form.account')" class="w-full" :class="errors.length && 'border-destructive'" v-bind="componentField" />
            </FormControl>
            <Transition enter-active-class="transition-opacity" enter-from-class="opacity-0" leave-active-class="transition-opacity" leave-to-class="opacity-0">
              <FormMessage class="absolute bottom-1 text-xs" />
            </Transition>
          </FormItem>
        </FormField>
        <FormField v-slot="{ componentField, errors }" name="password">
          <FormItem class="relative pb-6 space-y-0">
            <FormControl>
              <FaInput type="password" :placeholder="t('form.password')" class="w-full" :class="errors.length && 'border-destructive'" v-bind="componentField" />
            </FormControl>
            <Transition enter-active-class="transition-opacity" enter-from-class="opacity-0" leave-active-class="transition-opacity" leave-to-class="opacity-0">
              <FormMessage class="absolute bottom-1 text-xs" />
            </Transition>
          </FormItem>
        </FormField>
        <div class="flex-start-between gap-2">
          <FormField v-slot="{ componentField, errors }" name="code">
            <FormItem class="relative pb-6 space-y-0">
              <FormControl>
                <FaInput type="text" :placeholder="t('form.imgCaptcha')" class="w-full" :class="errors.length && 'border-destructive'" v-bind="componentField" />
              </FormControl>
              <Transition enter-active-class="transition-opacity" enter-from-class="opacity-0" leave-active-class="transition-opacity" leave-to-class="opacity-0">
                <FormMessage class="absolute bottom-1 text-xs" />
              </Transition>
            </FormItem>
          </FormField>
          <div class="flex-1">
            <img :src="imgCaptcha" alt="imgCaptcha" class="w-img" @click="getImgCaptcha">
          </div>
        </div>
        <div class="mb-4 flex-center-between">
          <div class="flex-center-start">
            <FormField v-slot="{ componentField }" type="checkbox" name="remember">
              <FormItem>
                <FormControl>
                  <FaCheckbox v-bind="componentField">
                    {{ t('remember') }}
                  </FaCheckbox>
                </FormControl>
              </FormItem>
            </FormField>
          </div>
          <!--          忘记密码 -->
          <!--          <FaButton variant="link" class="h-auto p-0" type="button" @click="emits('onResetPassword', form.values.username)"> -->
          <!--            {{ t('forget') }} -->
          <!--          </FaButton> -->
        </div>
        <FaButton :loading="loading" size="lg" class="w-full" type="submit">
          {{ t('form.login') }}
        </FaButton>
        <!--        <div class="mt-4 flex-center gap-2 text-sm">
          <span class="text-secondary-foreground op-50">{{ t('noAccount') }}</span>
          <FaButton variant="link" class="h-auto p-0" type="button" @click="emits('onRegister', form.values.username)">
            {{ t('register') }}
          </FaButton>
        </div> -->
      </form>
    </div>
    <div v-show="type === 'qrcode'">
      <div class="flex-col-center">
        <div id="wechatQRCode" style="height: 17.5rem;padding-top: 44px;" />
        <div class="mt-2 text-sm text-secondary-foreground op-50">
          {{ t('wechatQrcode') }}
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.w-img{
  width: 100%;
  height: 40px;
}
</style>
